#! /usr/bin/python
"""
This is the "abstraction layer ONE". It should "hide" the used interface from the
rest of the program. The idea is to replace this modul (and only this modul) in
order to use for example usb instead of the lpt port.
"""
import utils
import time, sys, os
try:
	import parallel
except:
	utils.err("Modul parallel not found! Please install pyparallel!")

MAX_TICKS_PER_CMD = 7

class LPT(object):
	def __init__(self):
		utils.log("Connected to printer Port...")
		try:
			self._p = parallel.Parallel()
		except:
			if os.name == "nt":
				utils.err("Cannot open parallel port!\n"+\
						"Have you installed giveio?\n")
			else:
				utils.err("Cannot open parallel port!\n"+\
						"You must load ppdev first:\n"+\
						"sudo rmmod lp\n"+\
						"sudo modprobe ppdev")
		self.delay = 0.001		#delay between commands
		self.reset()
	
	def set(self, data):
		self._p.setData(data)   #sets the data
		time.sleep(self.delay)  #give the robot time to respond
	
	def get(self):
		return 	self._p.getInAcknowledge() + \
				self._p.getInBusy() * 2 + \
				self._p.getInPaperOut() * 4 + \
				self._p.getInSelected() * 8 + \
				self._p.getInError() * 16
		
		return
	
	def reset(self):
		self.set(0) 			#resets pins
		time.sleep(0.05)        #wait more than 30ms
	
	def setdelay(self, delay):
		self.delay = delay
		utils.log("Delay set to "+str(delay))



class interface(LPT):
	def __init__(self):
		LPT.__init__(self)
		
	def connect(self, adress, dir, command=0):
		self.set((adress*16)+(dir>0)*8+(command))
		return self.get()
	
	def start(self):
		self.connect(0,15)	# start
	
	def move(self, list):
		# list = ( adress, dir, ticks )
		utils.log("executing command: "+str(list))
		
		# search for the longest command
		max_ticks = 0
		for adress, dir, ticks in list:
			if ticks > max_ticks:
				max_ticks = ticks
		
		cmd_count = max_ticks / MAX_TICKS_PER_CMD
		
		# split the commands in equal pieces
		for i in xrange(0, cmd_count):
			for adress, dir, ticks in list:
				print adress, "->", ticks / cmd_count, dir
				self.connect(adress, dir, ticks / cmd_count)
			self.start()
		
		# the rest...
		if ticks % cmd_count > 0:
			for adress, dir, ticks in list:
				print adress, "->", ticks % cmd_count, dir
				self.connect(adress, dir, ticks % cmd_count)
			self.start()




def run():
	sys.stdout.write(os.popen('clear').read()) # clears the terminal
	utils.log("Entering Runlevel 1")
	
	Port=interface()